// 引入express
const express = require("express");
// 这个组件用于接收post数据
const bodyParser = require("body-parser");
const jwt = require("jsonwebtoken");
// 创建服务器对象
const app = express();
const mysql = require("mysql");

// 创建连接池
const pool = mysql.createPool({
    connectionLimit: 10, // 设置连接池的连接数限制
    host: "localhost",
    user: "root",
    password: "123456",
    database: "desk",
    multipleStatements: true,
});

app.use(bodyParser.urlencoded({ extended: false }));

app.use(bodyParser.json());

// 解决跨域
app.all("*", function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "http://localhost:5173");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Content-Type");
    res.header("Access-Control-Allow-Methods", "*");
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

app.post("/login", (req, res) => {
    var phoneNumber = req.body.phoneNumber; // 获取手机号
    var passWord = req.body.passWord; // 获取密码

    if (!phoneNumber || !passWord) {
        res.send({
            code: 0,
            msg: "手机号和密码为必传参数...",
        });
        return;
    }

    const sqlStr = "SELECT * FROM user WHERE phoneNumber = ?"; // 查询手机号是否存在
    conn.query(sqlStr, [phoneNumber], (err, result) => {
        if (err) throw err;

        if (result.length === 0) {
            // 手机号不存在
            res.send({
                code: 0,
                msg: "手机号不存在",
            });
        } else {
            // 手机号存在，继续验证密码
            if (result[0].passWord === passWord) {
                // 密码正确，生成token
                var token = jwt.sign(
                    {
                        identity: result[0].identity,
                        userName: result[0].userName,
                    },
                    "secret",
                    { expiresIn: "1h" }
                );
                console.log(token);
                res.send({ code: 1, msg: "登录成功", token: token });
            } else {
                // 密码错误
                res.send({ code: 0, msg: "密码错误" });
            }
        }
    });
});


app.post("/register", (req, res) => {
    var userName = req.body.userName;
    var passWord = req.body.passWord;
    var phoneNumber = req.body.phoneNumber; // 添加手机号字段
    if (!userName || !passWord || !phoneNumber) {
        res.send({
            code: 0,
            msg: "用户名、密码和手机号为必传参数...",
        });
        return;
    }
    if (userName && passWord && phoneNumber) {
        const result = `SELECT * FROM user WHERE userName = '${userName}'`;
        conn.query(result, [userName], (err, results) => {
            if (err) throw err;
            if (results.length >= 1) {
                // 如果有相同用户名，则注册失败，用户名重复
                res.send({ code: 0, msg: "注册失败，用户名重复" });
            } else {
                const sqlStr =
                    "INSERT INTO user(userName, passWord, phoneNumber) VALUES (?, ?, ?)";
                conn.query(sqlStr, [userName, passWord, phoneNumber], (err, results) => {
                    if (err) throw err;
                    if (results.affectedRows === 1) {
                        res.send({ code: 1, msg: "注册成功" });
                    } else {
                        res.send({ code: 0, msg: "注册失败" });
                    }
                });
            }
        });
    }
});

// 连接数据库
pool.getConnection((err, connection) => {
    if (err) {
        console.error("连接数据库失败：", err);
    } else {
        console.log("连接数据库成功");

        // 将连接赋值给conn变量
        conn = connection;

        // 释放连接
        connection.release();

        // 开启监听
        app.listen(4000, () => {
            console.log("4000端口已经启动。。。");
        });
    }
});


